package app

import (
	"encoding/json"
	"fmt"
	"strings"

	x "gitcode.com/shexk/xframe/plugin"
)

type PluginList struct {
	PL map[string]string
}

type TopicMng struct {
	TL map[string]*PluginList
}

func NewTopic() *TopicMng {
	return &TopicMng{TL: make(map[string]*PluginList)}
}
func NewPluginList() *PluginList {
	return &PluginList{PL: make(map[string]string)}
}

func (t *TopicMng) AddTopic(name string) bool {
	if !t.IsExistTopic(name) {
		t.TL[name] = NewPluginList()
		return true
	}
	return false
}
func (t *TopicMng) IsExistTopic(name string) bool {
	if _, ok := t.TL[name]; ok {
		return true
	}
	return false
}
func (t *TopicMng) SelectTopic(name string) *PluginList {
	if v, ok := t.TL[name]; ok {
		return v
	}
	return nil
}
func (t *TopicMng) AddPluginFromTopic(topicname string, pluginname string) bool {
	pl := t.SelectTopic(topicname)
	if pl != nil {
		pl.PL[pluginname] = pluginname
		return true
	}
	return false
}
func (t *TopicMng) RemovePluginFromTopic(topicname string, pluginname string) bool {
	pl := t.SelectTopic(topicname)
	if pl != nil {
		delete(pl.PL, pluginname)
		return true
	}
	return false
}

func (t *TopicMng) RegisterTopic(topicname string, pluginname string) bool {
	t.AddTopic(topicname)
	return t.AddPluginFromTopic(topicname, pluginname)
}
func (t *TopicMng) UnRegisterTopic(topicname string, pluginname string) bool {
	return t.RemovePluginFromTopic(topicname, pluginname)
}

type cmd struct {
	Command string
	Name    []string
}

// 主题操作的命令为Json格式
// {Command:RegisterTopic/UnRegisterTopic,Name:[topicname_xxx1,xxx2]}
func (t *TopicMng) ProcessCommand(msg *x.PluginMsg) {
	var cc cmd
	err := json.Unmarshal(msg.Data, &cc)
	if err != nil {
		fmt.Println("反序列化失败:", err)
		return
	}

	if strings.Compare(cc.Command, "RegisterTopic") == 0 {
		for n := range cc.Name {
			t.RegisterTopic(cc.Name[n], msg.Sender.Name)
		}
	}
	if strings.Compare(cc.Command, "UnRegisterTopic") == 0 {
		for n := range cc.Name {
			t.UnRegisterTopic(cc.Name[n], msg.Sender.Name)
		}
	}
}
